package com.wxl.util;

import java.time.DateTimeException;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class SnowflakeIdWorker {
    /** 开始时间截 (2015-01-01) */
    private static final long twepoch = 1420041600000L;

    private final long workerId;
    private final long datacenterId = 0;
    private final Lock lock = new ReentrantLock();
    private long lastTimestamp = -1L;
    private long sequence = 0L;

    public SnowflakeIdWorker(long workerId) {
        if (workerId < 0 || workerId > 31) {
            throw new IllegalArgumentException("Worker ID must be 0-31");
        }
        this.workerId = workerId;
    }

    public long nextId() {
        lock.lock();
        try {
            long timestamp = timeGen();
            handleClockDrift(timestamp);
            handleSequence(timestamp);
            return buildId(timestamp);
        } finally {
            lock.unlock();
        }
    }

    private void handleClockDrift(long timestamp) {
        if (timestamp < lastTimestamp) {
            throw new RuntimeException("Clock moved backwards. Refusing to generate id");
        }
    }

    private void handleSequence(long timestamp) {
        if (timestamp == lastTimestamp) {
            sequence = (sequence + 1) & 0xFFF;
            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0L;
        }
        lastTimestamp = timestamp;
    }

    private long buildId(long timestamp) {
        return ((timestamp - twepoch) << 22)
                | (datacenterId << 17)
                | (workerId << 12)
                | sequence;
    }

    private long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            try {
                TimeUnit.MILLISECONDS.sleep(1);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            timestamp = timeGen();
        }
        return timestamp;
    }

    private long timeGen() {
        return System.currentTimeMillis();
    }


    /**
     * 根据雪花算法生成的id 找到对应的yyyyMM
     * @param id
     * @return
     */
    public static String getYYYYMM(long id) {
        try {
            return DateTimeFormatter.ofPattern("yyyyMM").withZone(ZoneId.of("Asia/Shanghai")).format(Instant.ofEpochMilli((id >>> 22) + twepoch));
        } catch (DateTimeException e) {
            throw new IllegalArgumentException("无效的雪花ID: " + id, e);
        }
    }

}